package com.example.italkapp2.controller.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.INotificationSideChannel;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;

import com.example.italkapp2.R;
import com.example.italkapp2.controller.adapter.GroupDetailAdapter;
import com.example.italkapp2.model.Model;
import com.example.italkapp2.model.bean.UserInfo;
import com.example.italkapp2.utils.Constant;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCursorResult;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.constants.EaseConstant;
import com.hyphenate.easeui.widget.EaseTitleBar;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.List;

//群详情页面
public class GroupDetailActivity extends Activity {
    private GridView gv_group_detail;
    private Button btn_exit_group;
    private EaseTitleBar titleBar;

    private EMGroup emGroup;
    private String emGroupOwner;
    private List<UserInfo> mUsers;
    private GroupDetailAdapter groupDetailAdapter;
    private GroupDetailAdapter.OnGroupDetailListener mOnGroupDetailListener=new GroupDetailAdapter.OnGroupDetailListener() {
        //添加群成员
        @Override
        public void onAddMembers() {
            Intent intent = new Intent(GroupDetailActivity.this, PickContactActivity.class);
            //传递群id
            intent.putExtra(Constant.GROUP_ID,emGroup.getGroupId());
            startActivityForResult(intent,2);
        }
        //删除群成员
        @Override
        public void onDeleteMember(UserInfo user) {
            Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        //从环信服务器删除该群的指定成员
                        EMClient.getInstance().groupManager().removeUserFromGroup(emGroup.getGroupId(),user.getHxid());
                        //更新页面
                        getMembersFromHxServer();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(GroupDetailActivity.this,"删除成员成功",Toast.LENGTH_SHORT).show();
                            }
                        });
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(GroupDetailActivity.this,"删除成员失败"+e.toString(),Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            });
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode==RESULT_OK){
            //获取回调后的要邀请的群成员信息
            String[] members = data.getStringArrayExtra("members");
            Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        //去环信服务器发送邀请信息
                        EMClient.getInstance().groupManager().addUsersToGroup(emGroup.getGroupId(),members);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(GroupDetailActivity.this,"发送邀请成功",Toast.LENGTH_SHORT).show();
                            }
                        });
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(GroupDetailActivity.this,"发送邀请失败"+e.toString(),Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_detail);

        initView();
        getData();
        initData();
        initListener();
    }

    private void initListener() {
        gv_group_detail.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        //判断当前是否是删除模式，是的话就切换回非删除模式
                        if(groupDetailAdapter.ismIsDeleteModel()){
                            groupDetailAdapter.setmIsDeleteModel(false);
                            //刷新页面
                            groupDetailAdapter.notifyDataSetChanged();
                        }
                        break;
                }
                return false;
            }
        });
    }

    private void initData() {
        //初始化button显示
        initButtonDisplay();
        
        //初始化gridView
        initGridView();

        //从环信服务器获取所有群成员
        getMembersFromHxServer();
    }

    private void getMembersFromHxServer() {

        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    EMGroup emGroupFromServer = EMClient.getInstance().groupManager().getGroupFromServer(emGroup.getGroupId());
                    List<String> members = emGroupFromServer.getMembers();

                    if(members!=null&&members.size()>=0){
                        mUsers=new ArrayList<UserInfo>();
                        //转换
                        for (String member:members){
                            UserInfo userInfo=new UserInfo(member);
                            mUsers.add(userInfo);
                        }
                    }

                    //更新页面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //刷新适配器
                            groupDetailAdapter.refresh(mUsers);
                        }
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(GroupDetailActivity.this,"获取群信息失败"+e.toString(),Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    private void initGridView() {
        //当前用户是群组或者是群公开了
        boolean isCanModify=EMClient.getInstance().getCurrentUser().equals(emGroupOwner)||emGroup.isPublic();
        groupDetailAdapter = new GroupDetailAdapter(this,isCanModify,mOnGroupDetailListener);

        gv_group_detail.setAdapter(groupDetailAdapter);
    }

    private void initButtonDisplay() {
        if(EMClient.getInstance().getCurrentUser().equals(emGroupOwner)){//群主的处理
            btn_exit_group.setText("解散群");
            btn_exit_group.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //去环信服务器解散群
                                EMClient.getInstance().groupManager().destroyGroup(emGroup.getGroupId());
                                //发送退群广播
                                exitGroupBroatCast();

                                //更新页面
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(GroupDetailActivity.this,"解散该群成功",Toast.LENGTH_SHORT).show();
                                        //结束页面
                                        finish();
                                    }
                                });
                            } catch (HyphenateException e) {
                                e.printStackTrace();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(GroupDetailActivity.this,"解散该群失败"+e.toString(),Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    });
                }
            });
        }else{//群成员
            btn_exit_group.setText("退群");
            btn_exit_group.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //告诉环信服务器已经离开该群
                                EMClient.getInstance().groupManager().leaveGroup(emGroup.getGroupId());
                                //发送退群广播
                                exitGroupBroatCast();

                                //更新页面
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(GroupDetailActivity.this,"离开该群成功",Toast.LENGTH_SHORT).show();
                                        //结束页面
                                        finish();
                                    }
                                });
                            } catch (HyphenateException e) {
                                e.printStackTrace();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(GroupDetailActivity.this,"离开该群失败"+e.toString(),Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    });
                }
            });
        }
    }

    //发送退群和解散群广播
    private void exitGroupBroatCast() {
        LocalBroadcastManager mLBM = LocalBroadcastManager.getInstance(GroupDetailActivity.this);
        Intent intent = new Intent(Constant.EXIT_GROUP);
        intent.putExtra(Constant.GROUP_ID,emGroup.getGroupId());
        mLBM.sendBroadcast(intent);

    }

    //获取传递过来的数据
    private void getData() {
        Intent intent = getIntent();
        String groupId=intent.getStringExtra(EaseConstant.EXTRA_CONVERSATION_ID);

        if(groupId==null){
            return;
        }else {
            emGroup= EMClient.getInstance().groupManager().getGroup(groupId);
            //获取群创建者
            while (emGroupOwner==null){
                emGroupOwner=emGroup.getOwner();
            }
        }
    }

    private void initView() {
        gv_group_detail=findViewById(R.id.gv_group_detail);
        btn_exit_group=findViewById(R.id.btn_exit_group);
        titleBar=findViewById(R.id.title_bar);
        titleBar.setLeftLayoutClickListener(v -> GroupDetailActivity.this.finish());
    }
}